package org.common.convert.tohtml;

import fr.opensagres.poi.xwpf.converter.core.ImageManager;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.common.convert.util.FileHelper;

import java.io.*;

/**
 * 将docx转换为html
 */
public class DocxToHtml {
    /**
     * 将docx转换为html
     * @param inputFilePath 源docx路径
     * @param outputFilePath 输出html路径
     * @throws Exception
     */
    public static void wordToHtml(String inputFilePath,String outputFilePath) throws Exception {

        System.out.println("outputFilePath:"+outputFilePath);
        File file = new File(inputFilePath);
        /* 判断是否为docx文件 */
        if (file.getName().endsWith(".docx") || file.getName().endsWith(".DOCX")) {
            // 1) 加载docx文档生成 XWPFDocument 对象
            XWPFDocument document = new XWPFDocument(new FileInputStream(file));
            // 2) 设置装换参数
            XHTMLOptions xhtmlOptions = XHTMLOptions.create();
            final int[] imageIndex = {0};
            // 设置图片管理器,把图片上传到服务器
            String rootPath = FileHelper.getPath(outputFilePath);
            xhtmlOptions.setImageManager(new ImageManager(new File(rootPath),""){
                // 图片访问路径
                private String imageUrl;

                @Override
                public void extract(String imagePath, byte[] imageData) throws IOException {
                    // 上传文件,设置图片url.  imageData:图片数据
                    imageUrl = imagePath;
                    imageIndex[0]++;
                    String fullPath = rootPath+imagePath;
                    FileHelper.createDir(fullPath);
                    File file = new File(fullPath);
                    try {
                        FileOutputStream out = new FileOutputStream(file);
                        out.write(imageData);
                        out.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public String resolve(String uri) {
                    // 返回图片访问路径
                    return imageUrl;
                }
            });

            // 转html输出
            OutputStream out = new FileOutputStream(outputFilePath);
            XHTMLConverter.getInstance().convert(document, out, xhtmlOptions);
            out.close();
//            FileHelper.convertFileToUTF8(outputFilePath);
        } else {
            throw new Exception("Enter only as MS Office 2007+ files");
        }
//        System.out.println("转换结束");
    }
}
